<?php

class ProductsController extends AController
{
    public $_model;

    public function filters()
    {
        return array(
            'accessControl',
        );
    }

    public function accessRules()
    {
        return array(
            array('allow',
                'actions' => array('view', 'index', 'special', 'all', 'new', 'search'),
                'users' => array('*'),
            ),
            array('allow',
                'actions' => array('admin', 'delete', 'create', 'update', 'view', 'sethome', 'saveorder', 'updateorder', 'deleteimage'),
                'users' => array('*'),
            ),
            array('deny', // deny all other users
                'users' => array('*'),
            ),
        );
    }

    public function beforeAction($action)
    {
        return parent::beforeAction($action);
    }

    public function actionView()
    {
        $this->render('view', array(
            'model' => $this->loadModel(),
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     */
    public function loadModel()
    {
        if ($this->_model === null) {
            if (isset($_GET['id']))
                $this->_model = Products::model()->findbyPk($_GET['id']);
            if ($this->_model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $this->_model;
    }

    public function actionCreate()
    {
        $model = new Products;

        //$this->performAjaxValidation($model);

        if (isset($_POST['Products'])) {
            if (!empty($_POST['Products']['subId'])) {
                $_POST['Products']['category_id'] = $_POST['Products']['subId'];
            }
            $model->attributes = $_POST['Products'];
            $model->stock = $_POST['Products']['stock'];
            $model->created_time = date('Y-m-d H:i:s');

            if ($model->save()) {
                $model->order = $model->product_id;
                $model->update();
                $this->redirect(array('/admin/products/update/id/' . $model->product_id));
            }
            //print_r($model->getErrors()); die;
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'products-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionUpdate($id)
    {
        $model = $this->loadModel();

        //$this->performAjaxValidation($model);

        if (isset($_POST['Products'])) {
            if (!empty($_POST['Products']['subId'])) {
                $_POST['Products']['category_id'] = $_POST['Products']['subId'];
            }
            $model->attributes = $_POST['Products'];
            $model->stock = $_POST['Products']['stock'];
            $model->updated_date = date('Y-m-d H:i:s');

            if ($model->save())
                $this->redirect(array('/admin/products/admin'));

        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     */
    public function actionDelete($id)
    {
        // we only allow deletion via POST request
        $listOrder = OrderPosition::model()->findAll("product_id ='" . $id . "'");
        if($listOrder) {
            OrderPosition::model()->deleteAll("product_id ='" . $id . "'");
            foreach($listOrder as $order) {
                Order::model()->deleteAll("order_id ='" . $order->order_id . "'");
            }
        }
        Image::model()->deleteAll("product_id ='" . $id . "'");

        $this->loadModel($id)->delete();
        Yii::app()->user->setFlash('message', "Xóa sản phẩm thành công!");

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $dataProvider = new CActiveDataProvider('Products');

        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Lists all models special.
     */
    public function actionSpecial()
    {
        $dataProvider = new CActiveDataProvider('Products', array(
            'criteria' => array(
                'condition' => 'is_special=1'
            )
        ));

        $this->render('special', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Lists all models special.
     */
    public function actionNew()
    {
        $dataProvider = new CActiveDataProvider('Products', array(
            'criteria' => array(
                'condition' => 'is_special=1',
                'order' => 'created_time DESC',
            )
        ));

        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Lists all models special.
     */
    public function actionAll()
    {
        if (Yii::app()->session['keyword']) {
            unset(Yii::app()->session['keyword']);
        }
        $sort = 'price asc';
        $sortDate = Yii::app()->request->getParam('date');
        $sortPrice = Yii::app()->request->getParam('price');

        if ($sortDate)
            $sort = 'created_time ' . $sortDate;
        if ($sortPrice)
            $sort = 'price ' . $sortPrice;

        $criteria = new CDbCriteria();
        if (!empty($_POST['keyword'])) {
            $keyword = $_POST['keyword'];
            $criteria->condition = "title LIKE :keyword";
            $criteria->params = array(':keyword' => "%$keyword%");
        }
        $criteria->order = $sort;

        $item_count = Products::model()->count($criteria);

        $pages = new CPagination($item_count);
        $pages->setPageSize(Yii::app()->params['listPerPage']);
        $pages->applyLimit($criteria); // the trick is here!

        $this->render('all', array(
            'model' => Products::model()->findAll($criteria), // must be the same as $item_count
            'item_count' => $item_count,
            'page_size' => Yii::app()->params['listPerPage'],
            'items_count' => $item_count,
            'pages' => $pages,
            'sort' => $sort
        ));
    }

    /**
     * Lists all models special.
     */
    public function actionSearch()
    {
        if (!empty($_POST['keyword'])) {
            Yii::app()->session['keyword'] = $_POST['keyword'];
        }

        $sort = 'price asc';
        $sortDate = Yii::app()->request->getParam('date');
        $sortPrice = Yii::app()->request->getParam('price');

        if ($sortDate)
            $sort = 'created_time ' . $sortDate;
        if ($sortPrice)
            $sort = 'price ' . $sortPrice;

        $criteria = new CDbCriteria();

        if (!empty(Yii::app()->session['keyword'])) {
            $keyword = Yii::app()->session['keyword'];
            $criteria->condition = "title LIKE :keyword";
            $criteria->params = array(':keyword' => "%$keyword%");
        }

        $criteria->order = $sort;

        $item_count = Products::model()->count($criteria);

        $pages = new CPagination($item_count);
        $pages->setPageSize(Yii::app()->params['listPerPage']);
        $pages->applyLimit($criteria); // the trick is here!

        $this->render('search', array(
            'model' => Products::model()->findAll($criteria), // must be the same as $item_count
            'item_count' => $item_count,
            'page_size' => Yii::app()->params['listPerPage'],
            'items_count' => $item_count,
            'pages' => $pages,
            'sort' => $sort
        ));
    }

    public function actionSethome($id=null, $show=0)
    {
        if($id) {
            if($show) $show = 0; else $show = 1;
            $model = Products::model()->updateAll(array('showhome'=>$show), 'product_id = ' . $id);
        }
        $this->redirect('/admin/products/admin');
    }
    /**
     * Manages all models.
     */
    public function actionAdmin($id=null)
    {
        $criteria = new CDbCriteria();
        
        if ($_GET['sort'] == 'asc') {
            $sort = '`order` ASC';
        } else {
            $sort = '`order` DESC';
        }
        
        $keyword='';
        $category = '';
        $filter = 'all';
        if (!empty($_POST['keyword'])) {
            $keyword = $_POST['keyword'];
            $criteria->condition = "title LIKE :keyword OR product_code LIKE :code";
            $criteria->params = array(':keyword' => "%$keyword%", ':code' => "%$keyword%");
        } else {
	    	if (!empty($_GET['filter'])) {
	            $filter = $_GET['filter'];
	            if($filter == 'home') {
	            	$criteria->condition = 'showhome = 1';
	            } else if($filter == 'new'){
					$criteria = new CDbCriteria();
	        		$criteria->condition = "created_time > DATE_ADD(CURDATE(), INTERVAL -31 DAY)";
	            } else if($filter == 'special') {
	            	$criteria->condition = 'new_price <> ""';
	            }
	        } else if (!empty($_GET['category'])) {
	        	$category = $_GET['category'];
	        	$categoryInfo = Category::model()->findbyPk($category);
        		if($categoryInfo['list_sub_id']) $categoryId = $category .','. $categoryInfo['list_sub_id'];
	        	else $categoryId = $category;
        		$criteria->condition = "category_id in ($categoryId)";
	        }
        }
	 
        $criteria->order = $sort;
        $item_count = Products::model()->count($criteria);
        
        $pages = new CPagination($item_count);
        $pages->setPageSize(Yii::app()->params['listPerPage']);
        $pages->applyLimit($criteria);  // the trick is here!

        //get list category
        //$categories = Category::model()->findAll('is_submenu = 2');                            </select>
                                    
        $this->render('admin',array(
            'model'=> Products::model()->findAll($criteria), // must be the same as $item_count
            'item_count'=>$item_count,
            'page_size'=>Yii::app()->params['listPerPage'],
            'items_count'=>$item_count,
            'pages'=>$pages,
            'sort'=>$sort,
            'keyword'=>$keyword,
        	'filter'=>$filter,
        	'categoryId'=>$category
        ));
    }
    
	/*
     * ajax update order category
     */
    public function actionUpdateOrder() 
    {
        if(isset($_POST['proId']))
        {
            $productsModel = new Products();
            $result = $productsModel->updateOrder($_POST['proId'], $_POST['proIdChange']);
        }
    }
    
    /*
     * save order subcategory
     */
    public function actionSaveOrder() 
    {
       if(is_array($_POST)) { 
            foreach($_POST['id'] as $key=>$id) {
                Products::model()->updateByPk($id, array('order'=>$_POST['order'][$key]));
            }
        }
        
        $this->redirect('/admin/products/admin');
    }
    
    public function actionDeleteImage()
    {
        if(isset($_POST['imgId']))
        {
            $result = Image::model()->deleteByPk($_POST['imgId']);
            return $result;
        }
    }
}
